package com.demo.richText.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HtmlUtil;
import com.demo.richText.pojo.Article;
import com.demo.richText.mapper.ArticleMapper;
import com.demo.richText.pojo.ArticleFile;
import com.demo.richText.pojo.vo.ReShowArticle;
import com.demo.richText.pojo.vo.ToSaveArticle;
import com.demo.richText.service.ArticleFileService;
import com.demo.richText.service.ArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 小王八
 * @since 2022-09-05
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleFileService articleFileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String toSaveArticle(ToSaveArticle toSaveArticle) {
        //1.生成文章id 插入图片article_id
        long articleId = IdUtil.getSnowflakeNextId();
        //2.文章内容转换
        //过滤HTML文本，防止XSS攻击 可用 会清理掉html元素标签 只留下文本
        //String articleContent = HtmlUtil.filter(toSaveArticle.getArticleContent());
        //表情包存储会报错
//        String escape = HtmlUtil.escape(toSaveArticle.getArticleContent());
        //html=>进行base32编码 把表情包 html的特殊转发 进行编码 数据量变为 8/5 倍
        //String encodeHex = Base32.encodeHex(toSaveArticle.getArticleContent());
        //html=>进行base64编码 把表情包 html的特殊转发 进行编码 数据量变为 4/3 倍
        String encodeUrlSafe = Base64.encodeUrlSafe(toSaveArticle.getArticleContent());
        //3.文章入数据库
        save(new Article()
                .setPkId(articleId)
                .setArticleName(toSaveArticle.getArticleName())
                .setArticleAuthor(toSaveArticle.getArticleAuthor())
                .setArticleContent(encodeUrlSafe)
        );
        //4.文章资源入数据库
        if (ObjectUtil.isNotEmpty(toSaveArticle.getArticleFileUrl())) {
            articleFileService.toSaveFile(toSaveArticle.getArticleFileUrl(), articleId);
        }
        return "文章保存成功";
    }

    @Override
    public ReShowArticle toShowArticle(Long articleId) {
        return ReShowArticle.toReShow(getById(articleId));
    }
}
